package com.starryx.blog.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.starryx.blog.NotFoundException;
import com.starryx.blog.dao.TypeMapper;
import com.starryx.blog.po.Type;
import com.starryx.blog.vo.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Collections;
import java.util.List;


@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeMapper typeMapper;


    @Override
    @Transactional
    public int saveType(Type type) {
        return typeMapper.save(type);
    }

    @Override
    public Type getType(Long id) {
        return typeMapper.findOneById(id);
    }

    @Override
    public Type getTypeByName(String name) {
        return typeMapper.findOneByName(name);
    }

    @Override
    public PageInfo<Type> listType(Page page) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize(), page.getOrderBy());
        return new PageInfo<Type>(typeMapper.findAll());
    }

    @Override
    public List<Type> listType() {
        return typeMapper.findAll();
    }

    @Override
    public List<Type> listTypeTop(Integer size) {
        List<Type> types = typeMapper.findAll();
        Collections.sort(types);
        Integer count = typeMapper.count();
        if(size > count){
            return types.subList(0, count);
        }else{
            return types.subList(0, size);
        }
    }

    @Override
    @Transactional
    public int updateType(Long id, Type type) {
        Type t = typeMapper.findOneById(id);
        if (t == null) {
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(type, t);      // 将 type 中的各属性赋值给 t 中的各属性，
        return typeMapper.update(type);
    }

    @Override
    @Transactional
    public void deleteType(Long id) {
        typeMapper.delete(id);
    }
}
